<template>
	<view class="container">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#ffffff" leftWidth="90rpx" rightWidth="90rpx" color="#333" :fixed="true" :padding="false" :border="navBorder" @clickLeft="$goBack(1)">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<view class="title">
				<!-- <view class="flex-r ac" v-if="barInfo && barInfo.logo && barInfo.title" @tap="$CHS.goBarHome(barInfo.barId)">
					<lazy-image class="bar-avatar" :src="barInfo.logo+'?imageView2/1/w/100/h/100/q/50'" type="bar" fit="cover"></lazy-image>
					<text class="text-large">{{barInfo.title}}</text>
				</view> -->
				<text >晒单详情</text>
			</view>
			<template slot="right">
			</template>
		</uni-nav-bar>
		<template v-if="!articleDetail.error">
			<scroll-view
				class="scroll-Y" 
				:style="scrollHeight"
				:scroll-y="true"
				:refresher-enabled="true" 
				:refresher-triggered="refreshing"
				refresher-default-style="none" 
				refresher-background="rgba(255, 255, 255, 0)"
				@refresherrefresh="refresh"
				@scroll="scroll"
			>
			<view class="body">
				<view class="post-des card flex-c">
					<view class="post-des-title thinborder">
						<view class="title-name">
							{{articleDetail.title}}
						</view>
						<view class="text-info color-grey flex-r ac jsb">
							<view class="date" v-if="articleDetail.createTime">
								<uni-dateformat :date="articleDetail.createTime" :threshold="[60000, 12*3600000]" format="MM-dd hh:mm"></uni-dateformat>
								{{new Date() - new Date(articleDetail.createTime.replace(/-/ig, '/')) < 12*3600000 ? '发布' : ''}}
							</view>
							<text class="views">{{articleDetail.virtualReadNum || 0}}人查看</text>
						</view>
					</view>
					<view class="post-des-head flex-r ac" @tap="$CHS.goExpertHome(articleDetail.userId, articleDetail.userType, articleDetail.type)">
						<view class="author-image border-round">
							<lazy-image class="inheritwh border-round" :src="articleDetail.userAvatar+'?imageView2/1/w/100/h/100/q/50'" type="expert" fit="cover"></lazy-image>
						</view>
						<view class="author-info flex-c">
							<text class="text-regular">{{articleDetail.userName}}</text>
						</view>
						<view class="author-fav flex-c" v-if="articleDetail.userType == 'expert'">
							<button class="favbtn active-msg" :class="{'nochat': articleDetail.userIdentity != 1}" type="warn" size="mini" v-if="articleDetail.followStatus == 1" @tap.stop="$CHS.goChat(articleDetail.userId, articleDetail.userIdentity)">私信</button>
							<button class="favbtn active-fav" type="warn" size="mini" @tap.stop="favExpert(articleDetail.userId)" v-else>关注</button>
						</view>
					</view>
					<view class="post-detail-body mt20" v-if="articleDetail.content">
						<view class="item-body-text">
							<view class="html-content" ref="freeContent" v-html="articleDetail.content"></view>
						</view>
					</view>
					<view class="post-detail-support mt30 flex-c ac" v-if="articleDetail.likeInfo">
						<image class="support-icon" :src="require('@/public/images/bar/dz_'+(articleDetail.likeInfo.likeStatus ? 'yd' : 'wd')+'.png')" mode="widthFix" @tap="supportSubmit(articleDetail.likeInfo.likeStatus)"></image>
						<view class="support-info mt20 text-small flex-r ac jc">
							<view class="support-user flex-r ac" :style="'width: '+[(articleDetail.likeInfo.avatarList.length - 1)*40 + 64]+'rpx;'" v-if="articleDetail.likeInfo.avatarList[0]">
								<lazy-image
									v-for="(avatar, index) in articleDetail.likeInfo.avatarList.slice(0, 5)"
									:key="index" 
									class="user-avatar border-round" 
									:style="'z-index: '+(5-index)+';left:'+(index*40)+'rpx;'" 
									:src="avatar"
									type="user"
									fit="cover"
								></lazy-image>
							</view>
							<text class="color-grey">{{articleDetail.likeInfo.likeCount || 0}}人已点赞</text>
						</view>
					</view>
				</view>
				<view class="post-comment" v-if="articleDetail.type">
					<CommentList
						:type="articleDetail.type+1" 
						:msgId="dynamicId" 
						:barId="barInfo && barInfo.barId" 
						:refresh="refreshing" 
						@more="showCommentPopup = true"></CommentList>
				</view>
			</view>
			</scroll-view>
			<template v-if="articleDetail.type">
				<view class="foot">
					<CommentInput 
						:popup.sync="inputPopup"
						:type="articleDetail.type+1" 
						:commentType="1" 
						:articleId="dynamicId" 
						:expertId="articleDetail.userId" 
						@success="commentSuccess"></CommentInput>
				</view>
				<CommentPopup
					:show.sync="showCommentPopup" 
					:type="articleDetail.type+1" 
					:msgId="dynamicId" 
					:expertId="articleDetail.userId" 
					:barId="barInfo && barInfo.barId" 
					:refresh="refreshing">
				</CommentPopup>
			</template>
		</template>
		<EmptyContent v-else top="250rpx" text="暂无数据" img="qsy_zwxl" :showRefresh="articleDetail.error" @refresh="getShareDetail(dynamicId)"></EmptyContent>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dynamicId: null, //晒单ID
				articleDetail: { //内容详情
					error: false
				},
				
				navBorder: false, //导航栏下边框
				refreshing: false, //下拉刷新状态
				
				barInfo: null, //球吧信息
				showCommentPopup: false, //评论列表弹窗状态
				inputPopup: false //评论输入框弹窗状态
			}
		},
		components: {
			CommentList: () => import('./components/ch-comment/ch-commentlist.vue'), //自定义评论列表
			CommentPopup: () => import('./components/ch-comment/ch-commentpopup.vue'), //自定义评论列表弹窗
			CommentInput: () => import('./components/ch-comment/ch-commentinput.vue') //留言输入框
		},
		computed: {
			user() {//用户信息
				return this.$store.state.user
			},
			scrollHeight() {//页面高度
				return `height:calc(var(--safe-height) - var(--navbar-height) - 96rpx);`;
			},
			canLeave() {//是否可以直接离开
				return !this.showCommentPopup && !this.inputPopup
			}
		},
		watch: {
			"articleDetail.content"(newValue, oldValue) { //富文本图片添加点击预览
				if(newValue){
					let imageList = this.getImgList(newValue)
					this.$nextTick(()=>{
						setTimeout(() => {
							this.addPreviewImage("freeContent", imageList)
						}, 500)
					})
				}
			}
		},
		onLoad() {
			let {did, barId, barName, barLogo} = this.$Route.query
			this.dynamicId = did
			if(this.dynamicId){
				if(barId){
					this.barInfo = {
						barId,
						logo: barLogo,
						title: barName
					}
				}
				this.getShareDetail(this.dynamicId)
			}else{
				console.log('非法请求');
				this.$CHS.errorRequest('index', '数据请求错误，请返回重试')
			}
			window.addEventListener("error", this.$CHS.imageLoadError, true)
		},
		beforeRouteLeave(to, from, next) {
			if(this.canLeave || to.name == 'experthome' || to.name == 'memberhome'){
				next();
			}else{
				if(this.showCommentPopup){
					this.showCommentPopup = false
				}else if(this.inputPopup){
					this.inputPopup = false
				}
				next(false);
			}
		},
		onUnload() {
			window.removeEventListener("error", this.$CHS.imageLoadError, true)
		},
		methods: {
			//页面滑动监听
			scroll(e) {
				if(e.detail.scrollTop > 10){
					this.navBorder = true
				}else{
					this.navBorder = false
				}
			},
			//下拉刷新
			refresh() {
				//更新刷新状态，加载数据
				this.refreshing = true
				this.getShareDetail(this.dynamicId)
				setTimeout(() => {
					this.refreshing = false
				}, 800)
			},
			//动态晒单详情
			getShareDetail(dynamicId) {
				this.$http.get({
					url: '/api/user/dynamic/info',
					data: {
						dynamicId,
						forumId: this.barInfo && this.barInfo.barId
					}
				}).then(data => {
					console.log(data);
					if(data.success && data.result){
						this.articleDetail = data.result
						//更新列表阅读数量
						uni.$emit('readNum', {num: data.result.virtualReadNum})
						//处理IOS多余Html代码
						if(data.result.content){
							this.articleDetail.content = this.$CHS.filterRichText(data.result.content)
						}
						if(this.articleDetail.content){
							this.articleDetail.content = this.articleDetail.content.replace(/width="[3-9][4-9][0-9]"/ig, '')
						}
					}else{
						this.$ShowToast({text: data.message || '晒单详情加载失败', type: 2})
						this.articleDetail.error = true
						/* setTimeout(()=>{
							this.$goBack(1)
						}, 1000) */
					}
				}).catch((err) => {
					console.log(err);
					this.articleDetail.error = true
				})
			},
			//关注专家
			favExpert(eid) {
				if(!this.$store.state.isLogin){
					this.$CHS.goUserLogin()
				}else{
					if(eid === this.isFaving){ //防止重复提交
						return
					}else{
						this.isFaving = eid
						this.$CHS.favExpert(eid).then( res => {
							console.log(res);
							this.articleDetail.followStatus = 1
						}).catch(err => {
							console.log(err);
							this.articleDetail.followStatus = 2
						}).finally(()=>{
							this.isFaving = null
						})
					}
				}
				
			},
			//点赞
			supportSubmit(status) {
				if(!this.isLogin){
					this.$CHS.goUserLogin()
				}else{
					if(!status){
						this.$http.post({
							url: '/api/forum/like/add',
							data: {
								commonId: this.dynamicId,
								forumId: this.barInfo && this.barInfo.barId,
								status: 1,
								type: 2
							}
						}).then(data => {
							console.log(data);
							if(data.success){
								this.$ShowToast({text: '点赞成功', type: 1})
								this.articleDetail.likeInfo.likeStatus = true
								this.articleDetail.likeInfo.likeCount += 1
								this.articleDetail.likeInfo.avatarList.unshift(this.user.avatar)
								this.articleDetail.likeInfo.avatarList = this.articleDetail.likeInfo.avatarList.slice(0, 5)
							}else{
								this.$ShowToast({text: data.message || '点赞失败，请稍后重试', type: 2})
							}
						})
					}else{
						uni.showToast({
							title: '您已经点赞过了',
							icon: 'none'
						})
					}
				}
				
			},
			//评论发布成功
			commentSuccess() {
				this.refreshing = true
				setTimeout(() => {
					this.refreshing = false
				}, 800)
			},
			// 提取图片
			getImgList(newValue) {
				let imgReg = /<img.*?(?:>|\/>)/gi; //匹配图片中的img标签
				let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配图片中的src
				let arr = newValue.match(imgReg); //筛选出所有的img
				let srcArr = [];
				if(arr){
					arr.forEach(item => {
						let src = item.match(srcReg);
						srcArr.push(src[1]);
					})
				}
				return srcArr
			},
			//图片预览
			addPreviewImage(refId, imageList){
				let contentDom = this.$refs[refId]?.$el
				if(contentDom){
					contentDom.addEventListener('click', (e) => {
						if(e.target.tagName.toUpperCase() == "IMG" && e.target.width > 50){
							uni.previewImage({
								current: e.target.currentSrc,
								urls: imageList,
								loop: true
							});
						}
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		.scroll-Y{
			/deep/ .uni-scroll-view-content{
				padding-top: 10rpx;
				height: calc(100% - 10rpx);
			}
		}
	}
	.body{
		padding: 10rpx 0 20rpx;
	}
	.card{
		background: #FFFFFF;
		margin-bottom: 20rpx;
		padding: 40rpx 20rpx;
	}
	.post-des{
		padding-top: 30rpx;
		margin-bottom: 0;
		.post-des-title{
			padding-bottom: 30rpx;
			//box-shadow: 0px 1rpx 0px 0px #EDEDED;
			.title-name{
				font-size: 36rpx;
				font-weight: 500;
				line-height: 54rpx;
				word-break: break-all;
			}
			.text-info{
				margin-top: 20rpx;
				.views{
					flex: 2;
					text-align: right;
				}
			}
		}
		.post-des-head{
			margin-top: 20rpx;
			.author-image{
				position: relative;
				width: 80rpx;
				height: 80rpx;
				background-color: #FFFFFF;
				background-size: 100%;
			}
			.author-info{
				flex: 2;
				width: 400rpx;
				margin-left: 20rpx;
				.info-detail{
					max-width: 400rpx;
					margin-top: 18rpx;
					font-size: 22rpx;
					color: #999999;
					line-height: 24rpx;
					overflow: hidden;
					text-overflow:ellipsis;
					white-space: nowrap;
				}
			}
			.author-fav{
				.favbtn{
					width: 120rpx;
					height: 60rpx;
					border-radius: 30rpx;
					font-size: 24rpx;
					padding: 0;
					margin: 0;
					box-sizing: border-box;
					&.active-fav{
						color: #0055FF;
						background: #E5EEFF;
						line-height: 60rpx;
						border: none;
					}
					&.active-msg{
						color: #0055FF;
						background: #FFFFFF;
						border: 2rpx solid #0055FF;
						line-height: 56rpx;
					}
					&.nochat{
						border-color: #99BBFF;
						color: #99BBFF;
					}
				}
			}
		}
		.post-detail-body{
			font-size: 30rpx;
			line-height: 52rpx;
			/deep/ .html-content{
				p:first-child{
					margin-top: 0;
				}
				p:last-child{
					margin-bottom: 0;
				}
			}
		}
		.post-detail-support{
			&.mt30{
				margin-top: 30rpx;
			}
			.support-icon{
				width: 240rpx;
			}
			.support-info{
				width: 100%;
				.support-user{
					position: relative;
					height: 64rpx;
					margin-right: 40rpx;
					.user-avatar{
						width: 64rpx;
						height: 64rpx;
						border: 4rpx solid #FFFFFF;
						box-sizing: border-box;
						position: absolute;
					}
				}
			}
		}
	}
	.post-other{
		margin-top: 50rpx;
		.post-other-head{
			align-items: center;
			justify-content: space-between;
			color: #333333;
			.head-left{
				line-height: 36rpx;
				font-size: 36rpx;
				font-weight: bold;
			}
			.head-right{
				height: 28rpx;
				align-items: center;
				font-size: 30rpx;
				font-weight: 400;
			}
		}
		.post-other-hot{
			/deep/ .article-list-item:last-child{
				margin-bottom: 0;
			}
			/deep/ .expert-share-list{
				padding: 30rpx 0 0;
			}
			/deep/ .expert-share-item:last-child{
				margin-bottom: 0;
			}
		}
	}
	.foot{
		max-width: $max-width;
		margin: $pc-margin;
		z-index: 997;
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		background: #FFFFFF;
		padding-bottom: var(--safe-area-inset-bottom);
	}
</style>
